/*
 *http://www.apache.org/licenses/LICENSE-2.0
 *Copyright (c) 2021 fullset
 *@ClassName LayTreeBuilder
 *@date 2021/6/29 17:58
 *@author: pangps
 *@Description TODO
 */
package com.fs.orm.layui;

import java.util.ArrayList;
import java.util.List;

public class TableTreeBuilder {

    private List<TableTree> treeList = new ArrayList<>();

    public TableTreeBuilder(List<TableTree> treeList) {
        this.treeList=treeList;
    }

    //建立树形结构
    public List<TableTree> builTree(){
        List<TableTree> treeMenus =new  ArrayList<>();
        for(TableTree menuNode : getRootNode()) {
            menuNode=buildChilTree(menuNode);
            treeMenus.add(menuNode);
        }
        return treeMenus;
    }

    //递归，建立子树形结构
    private TableTree buildChilTree(TableTree pNode){
        List<TableTree> chilMenus =new  ArrayList<>();
        for(TableTree menuNode : treeList) {
            if(menuNode.getParentId().equals(pNode.getId())) {
                chilMenus.add(buildChilTree(menuNode));
            }
        }
        pNode.setTreeList(chilMenus);
        return pNode;
    }

    //获取根节点
    private List<TableTree> getRootNode() {
        List<TableTree> rootMenuLists =new  ArrayList<>();
        for(TableTree menuNode : treeList) {
            if("0".equals(menuNode.getParentId())) {
                rootMenuLists.add(menuNode);
            }
        }
        return rootMenuLists;
    }
}
